# cmdd json格式转paddle 文本检测数据集格式
import json
import os

def transfrom_dict_to_str(target_dict):
    target_str = ''
    for item in target_dict:
        img_name = item['filename']
        lists = []
        # 把label 转化为transcription
        for cell in item['annotations']:
            dict02 = {}
            dict02['transcription'] = cell['text']
            a1 = [int(cell['x']),int(cell['y'])]  # 左上
            a2 = [int(cell['x']+cell['width']),int(cell['y'])]    # 右上
            a3 = [int(cell['x'] + cell['width']), int(cell['y'] + cell['height'])]    # 右下
            a4 = [int(cell['x']),int(cell['y']+cell['height'])]    # 左下
            dict02['points'] = [a1,a2,a3,a4]
            lists.append(dict02)
        lists = json.dumps(lists,ensure_ascii=False)
        target_str += img_name+'\t'+lists+'\n'
    return target_str

if __name__ == "__main__":
    # json文件的文件夹
    label_json = "I:/Images_OCR/cmrd_ocr/det/det_cmdd_pp/labels_src.json"
    f = open('I:/Images_OCR/cmrd_ocr/det/det_cmdd_pp/train.txt', 'w', encoding='utf-8')
    fd = open(label_json,'r',encoding='utf-8')
    data = fd.read()
    dict01 = json.loads(data)
    target_str = transfrom_dict_to_str(dict01)
    f.write(target_str)
    f.close()